package gew.services;

import gew.data.LoadRequest;
import java.util.Objects;
import javax.ejb.EJB;
import javax.ejb.Singleton;

@Singleton
public class TradeLoadArchiveService {

    private final static String LOCAL_FOLDER_ARCHIVE = "/home/gew/input-archive/";
    //private final static String SHARE_FOLDER_ARCHIVE = "smb://gew-web/input-archive/";
    private final static String LOCAL_FOLDER_ARCHIVE_ERR = "/home/gew/input-archive/err/";
    private final static Integer LOCAL_LOAD_REQUEST_ID_ERROR = -1;
    private final static String ARCHIVE_FILE_EXTENSION = ".7z";
    private final static String INPUT_FILE_EXTENSION = ".txt";
    private final static Integer CMD_TIMEOUT = 60000;
    private final static Integer CMD_STEP = 500;

    @EJB
    private QueryService queryService;

    public void execute() {
        while (TradeImportData.getFilesCount(LOCAL_FOLDER_ARCHIVE, ARCHIVE_FILE_EXTENSION) > 0) {
            executeNextRequest();
        }
    }

    public Boolean executeNextRequest() {
        System.out.println("***** Start Trade Load Archive Service *****");

        // Попытаться найти файл с расширением архива
        String archiveFile = TradeImportData.getFileName(LOCAL_FOLDER_ARCHIVE, ARCHIVE_FILE_EXTENSION);
        Boolean result = !archiveFile.isEmpty();
        if (!result) {
            System.out.println("File " + LOCAL_FOLDER_ARCHIVE + "*" + ARCHIVE_FILE_EXTENSION + " not found");
            return result;
        }

        // Разархивировать файл
        String inputFile = archiveFile.replace(ARCHIVE_FILE_EXTENSION, INPUT_FILE_EXTENSION);
        System.out.println("***** Archive: " + archiveFile + " *****");
        result = TradeImportData.extractArchive(archiveFile, inputFile, LOCAL_FOLDER_ARCHIVE, CMD_TIMEOUT, CMD_STEP);
        if (!result) {
            System.out.println("* exit :( *");
            TradeImportData.moveFile(archiveFile, LOCAL_FOLDER_ARCHIVE, LOCAL_FOLDER_ARCHIVE_ERR, CMD_STEP, CMD_STEP);
            return result;
        }

        // Создать в БД loadRequest
        result = TradeImportData.createNewLocalLoadRequest(inputFile, queryService, LoadRequest.STATUS_LOCAL_READY) > 0;
        if (!result) {
            System.out.println("* exit :( *");
            TradeImportData.moveFile(archiveFile, LOCAL_FOLDER_ARCHIVE, LOCAL_FOLDER_ARCHIVE_ERR, CMD_STEP, CMD_STEP);
            TradeImportData.moveFile(inputFile, LOCAL_FOLDER_ARCHIVE, LOCAL_FOLDER_ARCHIVE_ERR, CMD_STEP, CMD_STEP);
            return result;
        }

        // Получить идентификатор созданного loadRequest
        Integer loadRequestId = TradeImportData.getCreatedLocalLoadRequestId(inputFile, queryService, LoadRequest.STATUS_LOCAL_READY, LOCAL_LOAD_REQUEST_ID_ERROR);
        result = !Objects.equals(loadRequestId, LOCAL_LOAD_REQUEST_ID_ERROR);
        if (!result) {
            System.out.println("* exit :( *");
            TradeImportData.moveFile(archiveFile, LOCAL_FOLDER_ARCHIVE, LOCAL_FOLDER_ARCHIVE_ERR, CMD_STEP, CMD_STEP);
            TradeImportData.moveFile(inputFile, LOCAL_FOLDER_ARCHIVE, LOCAL_FOLDER_ARCHIVE_ERR, CMD_STEP, CMD_STEP);
            return result;
        }

        // Изменить статус нового loadRequest
        result = TradeImportData.updateLoadRequestStatus(queryService, loadRequestId, LoadRequest.STATUS_LOCAL_EXECUTION);
        if (!result) {
            System.out.println("* exit :( *");
            TradeImportData.moveFile(archiveFile, LOCAL_FOLDER_ARCHIVE, LOCAL_FOLDER_ARCHIVE_ERR, CMD_STEP, CMD_STEP);
            TradeImportData.moveFile(inputFile, LOCAL_FOLDER_ARCHIVE, LOCAL_FOLDER_ARCHIVE_ERR, CMD_STEP, CMD_STEP);
            return result;
        }

        // Вызвать процедуру импорта данных из файла
        System.out.println("***** Import Data From file " + inputFile + " *****");
        result = TradeImportData.importFileData2(inputFile, LOCAL_FOLDER_ARCHIVE, queryService, loadRequestId);
        if (!result) {
            System.out.println("* exit :( *");
            TradeImportData.moveFile(archiveFile, LOCAL_FOLDER_ARCHIVE, LOCAL_FOLDER_ARCHIVE_ERR, CMD_STEP, CMD_STEP);
            TradeImportData.moveFile(inputFile, LOCAL_FOLDER_ARCHIVE, LOCAL_FOLDER_ARCHIVE_ERR, CMD_STEP, CMD_STEP);
            TradeImportData.updateLoadRequestStatus(queryService, loadRequestId, LoadRequest.STATUS_LOCAL_LOAD_ERROR);
            return result;
        }

        // Удалить файл
        System.out.println("***** Remove file " + inputFile + " *****");
        result = TradeImportData.removeFile(inputFile, LOCAL_FOLDER_ARCHIVE, CMD_TIMEOUT, CMD_STEP);
        if (!result) {
            System.out.println("* exit :( *");
            TradeImportData.moveFile(inputFile, LOCAL_FOLDER_ARCHIVE, LOCAL_FOLDER_ARCHIVE_ERR, CMD_STEP, CMD_STEP);
            TradeImportData.updateLoadRequestStatus(queryService, loadRequestId, LoadRequest.STATUS_LOCAL_LOAD_ERROR);
            return result;
        }

        // Удалить архив
        System.out.println("***** Remove archive " + archiveFile + " *****");
        result = TradeImportData.removeFile(archiveFile, LOCAL_FOLDER_ARCHIVE, CMD_TIMEOUT, CMD_STEP);
        if (!result) {
            System.out.println("* exit :( *");
            TradeImportData.moveFile(archiveFile, LOCAL_FOLDER_ARCHIVE, LOCAL_FOLDER_ARCHIVE_ERR, CMD_STEP, CMD_STEP);
            TradeImportData.updateLoadRequestStatus(queryService, loadRequestId, LoadRequest.STATUS_LOCAL_LOAD_ERROR);
            return result;
        }

        // Обновить статус loadRequest на Завершён
        TradeImportData.updateLoadRequestStatus(queryService, loadRequestId, LoadRequest.STATUS_LOCAL_COMPLETED);

        System.out.println("*****   End Trade Load Archive Service *****");

        return result;
    }

}
